import psycopg2

_host = "192.168.6.124"
_port = "5432"
_database = "recovery"
_user = "postgres"
_password = "postgres"

def overall(uuid :str = None,task_id :str = None ):
    if task_id == None or uuid == None:
        pass
        return {"status":0,"task_id":task_id,"uuid":uuid,"msg":"task_id or uuid is None"}
    try:
        # 连接到 PostgreSQL 数据库
        conn = psycopg2.connect(
        host = _host,
        port = _port,
        database = _database,
        user = _user,
        password = _password
    )
    except:
        return {"status":0,"task_id":task_id,"uuid":uuid,"msg":"database connect refused"}
    # 创建游标对象
    cursor = conn.cursor()

    # 执行查询
    cursor.execute("SELECT * FROM publish_massing_conf where \"taskId\" = '{}' and uuid = '{}';".format(task_id,uuid))
    
    # 获取查询结果
    result = cursor.fetchall()
    # 关闭游标和连接
    cursor.close()
    conn.close()
    if len(result) == 0:
        return {"status":0,"task_id":task_id,"uuid":uuid,"msg":"task_id or uuid not fund"}
    else:
        pv_dict = {}
        for datas in result[0][4]:
            for data in datas["modeConfs"]:
                try:
                    pv_dict[data["disName"]]={"defaultValue":data["defaultValue"]}
                except:
                    continue
        Lock_dict = {"data":{},"version":{}}
        for datas in result[0][13]['groups']:
            Lock_dict["data"][datas["groupName"]]=datas["binary_code"]
            Lock_dict["version"][datas["versionName"]] = datas["versionNo"]
            for data in datas["pvInstances"]:
                try:
                    pv_dict[data["disName"]]["pv"] = data["name"]
                except:
                    continue
        return {"status":1,"task_id":task_id,"uuid":uuid,"data":{"overallName":result[0][1],"overallDesc":result[0][2],"subSystems":pv_dict,"Lock":Lock_dict}}
    
    
def pv_SELECT(name :str = None):
    #if id == None:
        #return {"status":0,"pv_name":name,"msg":"pv_name is None"}
    try:
        # 连接到 PostgreSQL 数据库
        conn = psycopg2.connect(
        host = _host,
        port = _port,
        database = _database,
        user = _user,
        password = _password
    )
    except:
        return {"status":0,"pv_name":name,"msg":"database connect refused"}
    # 创建游标对象
    cursor = conn.cursor()

    # 执行查询
    cursor.execute("SELECT * FROM pv_instance where name = '{}'".format(name))
    cursor.execute("SELECT * FROM pv_instance")
    # 获取查询结果
    result = cursor.fetchall()
    if len(result) == 0:
        return {"status":0,"pv_name":name,"msg":"name not fund"}
    else:
        return {"status":1,"pv_name":name,"data":result}
    # 关闭游标和连接
    cursor.close()
    conn.close()
if __name__=="__main__":
    overall('01ff7972-5e4f-4716-ae80-192cc7794b04','20240415171629')
